package com.bx.implatform.util;

import com.alibaba.fastjson.JSON;
import com.bx.implatform.dto.LgkUserInfoDTO;
import com.bx.implatform.exception.GlobalException;
import com.bx.implatform.vo.LgkUserInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @author chilson
 * @date 2025-04-12 21:42:56
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LgkRequestUtils {
    private final RestTemplate restTemplate;
    @Value("${lgk.userInfoUrl}")
    private String userInfoUrl;
    @Value("${lgk.chatNoticeUrl}")
    private String chatNoticeUrl;
    @Value("${lgk.secret}")
    private String secret;

    public LgkUserInfoVO getUerInfo(String authToken, String ua){
        LgkUserInfoVO lgkUserInfoVO = new LgkUserInfoVO();
        LgkUserInfoDTO userInfo;
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Token", authToken);
            if (ua != null) {
                headers.set("User-Agent", ua);
            }

            HttpEntity<Void> requestEntity = new HttpEntity<>(null, headers);

            ResponseEntity<LgkUserInfoDTO> response = restTemplate.exchange(
                    userInfoUrl,
                    HttpMethod.GET,
                    requestEntity,
                    new ParameterizedTypeReference<LgkUserInfoDTO>() {}
            );
            userInfo = response.getBody();
        } catch (HttpClientErrorException e) {
            // 处理 4xx 错误
            throw new RuntimeException("客户端错误: " + e.getStatusCode(), e);
        } catch (HttpServerErrorException e) {
            // 处理 5xx 错误
            throw new RuntimeException("服务端错误: " + e.getStatusCode(), e);
        } catch (RestClientException e) {
            // 处理网络错误（如超时）
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }

        if (userInfo == null || userInfo.getData() == null || (
                userInfo.getData().get("userId") == null && userInfo.getData().get("adminId") == null)) {
            throw new GlobalException("登录凭证已失效");
        }
        Map<String, Object> data = userInfo.getData();
        Integer lgkUserId = (Integer) data.get("userId");
        if (lgkUserId == null ){
            lgkUserId = (Integer) data.get("adminId");
        }
        lgkUserInfoVO.setUserId(lgkUserId);
        lgkUserInfoVO.setImUserId(Long.valueOf((Integer) data.get("imUserId")));
        lgkUserInfoVO.setImNickName((String) data.get("imUserName"));

        return lgkUserInfoVO;
    }

    public void sendChatNotice(Long senderId, Long receiverId, String content){
        try {
            Map<String, Object> body = new HashMap<>();
            body.put("imSenderId", senderId);
            body.put("imReceiverId", receiverId);
            body.put("content", content);
            HttpEntity<String> requestEntity = new HttpEntity<>(JSON.toJSONString(body));

            ResponseEntity<LgkUserInfoDTO> response = restTemplate.exchange(
                    chatNoticeUrl + "/" + secret,
                    HttpMethod.POST,
                    requestEntity,
                    new ParameterizedTypeReference<>() {}
            );
        } catch (HttpClientErrorException e) {
            // 处理 4xx 错误
            throw new RuntimeException("客户端错误: " + e.getStatusCode(), e);
        } catch (HttpServerErrorException e) {
            // 处理 5xx 错误
            throw new RuntimeException("服务端错误: " + e.getStatusCode(), e);
        } catch (RestClientException e) {
            // 处理网络错误（如超时）
            throw new RuntimeException("请求失败: " + e.getMessage(), e);
        }
    }
}
